﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;

namespace EnvirEmulator
{
    public partial class Main : Form
    {
        Queue<DataBlock> m_data = new Queue<DataBlock>();

        DateTime m_baseTime = new DateTime();

        System.Timers.Timer tim = new System.Timers.Timer();

        public Main()
        {
            InitializeComponent();
            tim.Interval = 10;
            tim.Elapsed += new System.Timers.ElapsedEventHandler(tim_Elapsed);

            ConfigureSerialPort();
        }

        /// <summary>
        /// 
        /// </summary>
        private void ConfigureSerialPort()
        {
            serialPort1.PortName = "COM8";
            serialPort1.BaudRate = 57600;
            serialPort1.DataBits = 8;
            serialPort1.StopBits = System.IO.Ports.StopBits.One;
            serialPort1.Parity = System.IO.Ports.Parity.None;
            serialPort1.Open();
        }

        delegate void post();

        void tim_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DataBlock db;


            if (m_data.Count > 0)
            {
                db = m_data.Dequeue();
                tim.Interval = (db.TimeInterval * 1000) + 1;
                post myDel = () => { richTextBox1.Text += db.DataPacket + Environment.NewLine; };
                richTextBox1.BeginInvoke(myDel);
                serialPort1.WriteLine(db.DataPacket);
            }
            else
            {
                tim.Stop();
            }
        }

        private void DisplayText(string displayText)
        {
            richTextBox1.Text += displayText;
        }

        private void btnReadFile_Click(object sender, EventArgs e)
        {
            string startTime = null;
            DateTime newStartTime = DateTime.Now;

            StreamReader sr = new StreamReader(@"C:\Data\Fraser\code\envir2plotwatt\EnvirEmulator\energymonitor.log");
            while (!sr.EndOfStream)
            {
                string dataString = sr.ReadLine();
                XmlReader reader = XmlReader.Create(new StringReader(dataString));
                string time = null;
                string power = null;
                
                reader.Read();
                if (reader.IsStartElement())
                {
                    if (reader.Name == "msg")
                    {
                        reader.ReadToDescendant("time");
                        time = reader.ReadString();
                        reader.ReadToNextSibling("ch1");
                        reader.ReadToDescendant("watts");
                        power = reader.ReadString();

                        if (power != null && startTime == null)
                        {
                            startTime = time;
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(power))
                {
                    DateTime dt = DateTime.Parse(time);
                    int secondDelay = 0;

                    if (m_baseTime.Year == 1)
                    {
                        secondDelay = 0;
                    }
                    else
                    {
                        secondDelay = (int)(dt.Subtract(m_baseTime)).TotalSeconds;
                    }

                    m_baseTime = dt;

                    //replace the time in the file so that we can get a real time rather than always replaying the same time from the file
                    DateTime newTime = newStartTime.Add(dt.Subtract(DateTime.Parse(startTime)));
                    string replacementTime = newTime.ToLongTimeString();
                    dataString = dataString.Replace(time, replacementTime);

                    m_data.Enqueue(new DataBlock() { TimeInterval = secondDelay, DataPacket = dataString });
                }
            }

            if (m_data.Count > 0)
            {
                tim.Start();
            }
        }
    }
}
